import 'dart:io';

import 'package:desktop_drop/desktop_drop.dart';
import 'package:excel_utils/extend/string_extend.dart';
import 'package:excel_utils/pages/cpc_report/bean/china_post_file_bean.dart';
import 'package:excel_utils/pages/cpc_report/bean/fee_item_bean.dart';
import 'package:excel_utils/pages/cpc_report/bean/waybill_managent_bean.dart';
import 'package:excel_utils/pages/cpc_report/cpc_file/bean/cpc_file_result_bean.dart';
import 'package:excel_utils/pages/cpc_report/cpc_file/bloc/cpc_file_bloc.dart';
import 'package:excel_utils/pages/cpc_report/cpc_file/bloc/cpc_file_event.dart';
import 'package:excel_utils/pages/cpc_report/cpc_file/bloc/cpc_file_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../bean/china_post_luggage_bean.dart';

class ChkFilePage extends StatefulWidget {
  const ChkFilePage({super.key});

  @override
  State<ChkFilePage> createState() => _ChkFilePageState();
}

class _ChkFilePageState extends State<ChkFilePage> {
  CpcFileBloc? _cpcReportBloc;

  File? _waybillManagementFile;
  String? waybillManagementName;
  bool waybillManagementLoadingState = false;
  double waybillManagementProgress = 0.0;
  List<WaybillManagementBean> waybillManagementList = [];

  File? _chinaPostFileFile; // 中郵行李
  String? chinaPostFileName;
  bool chinaPostFileLoadingState = false;
  double chinaPostFileProgress = 0.0;
  List<ChinaPostFileBean> chinaPostFileList = [];

  File? _feeItemFile;
  String? feeItemName;
  bool feeItemLoadingState = false;
  double feeItemProgress = 0.0;
  List<FeeItemBean> feeItemList = [];

  List<String> headeData = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u"];
  List<CpcFileResultBean> cpcFileResultList = [];
  File? writeFile;
  String? writeName = "Sheet1";
  bool writeFileLoadingState = false;
  bool mergeLoadingState = false; // 是否在合并
  double? margeProgress = 0.0;
  double? writeProgress = 0.0;
  String writeMsg = "";

  showSnackBar(Text msg) {
    ScaffoldMessenger.of(context)
      ..hideCurrentSnackBar()
      ..showSnackBar(SnackBar(content: msg));
  }

  @override
  Widget build(BuildContext context) {
    return BlocProvider<CpcFileBloc>(
      create: (BuildContext context) => _cpcReportBloc ?? CpcFileBloc(),
      child: BlocBuilder<CpcFileBloc, CpcFileAnalysisMergeState>(
        builder: (BuildContext context, CpcFileAnalysisMergeState state) {
          _cpcReportBloc = _cpcReportBloc ?? context.read<CpcFileBloc>();

          if (state is CpcFileAnalysisMergeState) {
            waybillManagementList = state.waybillManagementList;
            waybillManagementProgress = state.waybillManagementProgress;
            chinaPostFileList = state.chinaPostFileList;
            chinaPostFileProgress = state.chinaPostFileProgress;

            feeItemList = state.feeItemList;
            feeItemProgress = state.feeItemProgress;

            // 提取数据
            mergeLoadingState = state.mergeLoadingState;
            margeProgress = state.mergeProgress;
            cpcFileResultList = state.cpcFileResult ?? [];

            writeFileLoadingState = state.writeLoadingState;
            writeProgress = state.writeProgress;
            writeMsg =   state.writeMsg;

          }

          return _buildUI();
        },
      ),
    );
  }

  Widget _buildUI() {
    return Scaffold(
        body: Container(
          child: SingleChildScrollView(
            child: Column(
              children: [
                Text(
                  "注意，文件格式必须为xlsx格式",
                  style: TextStyle(fontSize: 20, color: Colors.red),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Container(
                      width: 200,
                      height: 150,
                      child: Column(
                        children: [
                          Expanded(
                              child: DropTarget(
                                  onDragDone: (data) {
                                    // 判断是否为xlsx格式
                                    // if (data.files.first.path.endsWith(".xlsx")) {
                                    //   showSnackBar(Text("请选择   .xlsx 文件的格式"));
                                    //   return;
                                    // }
                                    // 运单管理
                                    _waybillManagementFile = File(data.files.first.path);
                                    _cpcReportBloc?.add(CpcFileWaybillManagementEvent(file: _waybillManagementFile, sheetName: waybillManagementName ?? "Sheet1"));
                                    // 开始解析
                                    setState(() {});
                                  },
                                  child: Container(
                                    color: Colors.blue.withOpacity(0.4),
                                    child: _waybillManagementFile != null
                                        ? Text("${_waybillManagementFile!.path.split('\\').last}")
                                        : const Center(
                                            child: Text("運單管理，移动文件到此处"),
                                          ),
                                  ))),
                          SizedBox(
                            height: 50,
                            child: TextField(
                              onChanged: (value) {
                                waybillManagementName = value;
                              },
                              decoration: InputDecoration(
                                hintText: "默认是Sheet1",
                                border: OutlineInputBorder(),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      width: 200,
                      height: 150,
                      child: Column(
                        children: [
                          Expanded(
                              child: DropTarget(
                                  onDragDone: (data) {
                                    // 判断是否为xlsx格式
                                    // if (data.files.first.path.endsWith(".xlsx")) {
                                    //   showSnackBar(Text("请选择   .xlsx 文件的格式"));
                                    //   return;
                                    // }
                                    _chinaPostFileFile = File(data.files.first.path);
                                    _cpcReportBloc?.add(CpcFileChinaPostFileEvent(file: _chinaPostFileFile, sheetName: chinaPostFileName ?? "Sheet1"));
                                    setState(() {});
                                  },
                                  child: Container(
                                    color: Colors.blue.withOpacity(0.4),
                                    child: _chinaPostFileFile != null ? Text("${_chinaPostFileFile!.path.split('\\').last}") : const Center(child: Text("中郵文件，移动文件到此处")),
                                  ))),
                          SizedBox(
                            height: 50,
                            child: TextField(
                              onChanged: (value) {
                                chinaPostFileName = value;
                              },
                              decoration: InputDecoration(
                                hintText: "默认是Sheet1",
                                border: OutlineInputBorder(),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      width: 200,
                      height: 150,
                      child: Column(
                        children: [
                          Expanded(
                            child: DropTarget(
                                onDragDone: (data) {
                                  // 判断是否为xlsx格式
                                  // if (data.files.first.path.endsWith(".xlsx")) {
                                  //   showSnackBar(Text("请选择   .xlsx 文件的格式"));
                                  //   return;
                                  // }
                                  _feeItemFile = File(data.files.first.path);
                                  _cpcReportBloc?.add(CpcFileFeeitemlistEvent(file: _feeItemFile, sheetName: feeItemName ?? "Sheet1"));
                                  setState(() {});
                                },
                                child: Container(
                                  color: Colors.blue.withOpacity(0.4),
                                  child: _feeItemFile != null ? Text("${_feeItemFile!.path.split('\\').last}") : const Center(child: Text("FeeItem，移动文件到此处")),
                                )),
                          ),
                          SizedBox(
                            height: 50,
                            child: TextField(
                              onChanged: (value) {
                                feeItemName = value;
                              },
                              decoration: InputDecoration(
                                hintText: "默认是Sheet1",
                                border: OutlineInputBorder(),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                Text("数据预览", style: TextStyle(fontSize: 20, color: Colors.red)),
                Container(
                  decoration: BoxDecoration(border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(10)),
                  padding: EdgeInsets.all(10),
                  margin: EdgeInsets.all(10),
                  height: 160,
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        Text("运单管理 ${waybillManagementList.length}"),
                        if (waybillManagementLoadingState) LinearProgressIndicator(value: waybillManagementProgress, color: Colors.blue),
                        Table(
                          children: [
                            const TableRow(children: [TableCell(child: Text("運單編號")), TableCell(child: Text("客戶名稱")), TableCell(child: Text("訂單地址")), TableCell(child: Text("入場時間"))]),
                            ...waybillManagementList.map((element) {
                              return TableRow(children: [
                                TableCell(child: Text("${element.waybillNumber}")),
                                TableCell(child: Text("${element.accountName}")),
                                TableCell(child: Text("${element.orderAddress}", maxLines: 1)),
                                TableCell(child: Text("${element.entryDate}")),
                              ]);
                            })
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
                Container(
                  decoration: BoxDecoration(border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(10)),
                  width: double.infinity,
                  height: 160,
                  padding: EdgeInsets.all(10),
                  margin: EdgeInsets.all(10),
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        Text("中邮文件 ${chinaPostFileList.length}"),
                        if (chinaPostFileLoadingState) LinearProgressIndicator(value: chinaPostFileProgress, color: Colors.blue),
                        Table(
                          children: [
                            TableRow(children: [
                              TableCell(child: Text("billedDate")),
                              TableCell(child: Text("amount")),
                              TableCell(child: Text("trackingNo")),
                              TableCell(child: Text("cXCAmount")),
                              TableCell(child: Text("localCurrentAction")),
                            ]),
                            ...chinaPostFileList.map((element) {
                              return TableRow(children: [
                                TableCell(child: Text("${element.billedDate}")),
                                TableCell(child: Text("${element.amount}")),
                                TableCell(child: Text("${element.trackingNo}")),
                                TableCell(child: Text("${element.cXCAmount}")),
                                TableCell(child: Text("${element.localCurrentAction}")),
                              ]);
                            }),
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
                Container(
                  decoration: BoxDecoration(border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(10)),
                  width: double.infinity,
                  height: 160,
                  padding: EdgeInsets.all(10),
                  margin: EdgeInsets.all(10),
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        Text("FeeItem数据 ${feeItemList.length}"),
                        if (feeItemLoadingState) LinearProgressIndicator(value: feeItemProgress, color: Colors.blue),
                        Table(
                          children: [
                            TableRow(children: [TableCell(child: Text("跟踪号码")), TableCell(child: Text("重量(KG)")), TableCell(child: Text("费用"))]),
                            ...feeItemList.map((element) {
                              return TableRow(children: [TableCell(child: Text("${element.trackingNumber}")), TableCell(child: Text("${element.kg}")), TableCell(child: Text("${element.price}"))]);
                            })
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
                Row(
                  children: [
                    SizedBox(
                      width: 10,
                    ),
                    ElevatedButton(
                        onPressed: () {
                          _cpcReportBloc?.add(CpcFileDataMergeEvent(waybillManagementList: waybillManagementList, chinaPostFileList: chinaPostFileList, feeItemList: feeItemList));
                        },
                        child: Text("数据提取合并")),
                    SizedBox(width: 10),
                    ElevatedButton(
                        onPressed: () {
                          StringBuffer sb = StringBuffer();
                          for (var element in cpcFileResultList) {
                            sb.write("${element.a ?? ""}\t");
                            sb.write("${element.b ?? ""}\t");
                            sb.write("${element.c ?? ""}\t");
                            sb.write("'${element.d ?? ""}\t");
                            sb.write("'${element.e ?? ""}\t");
                            sb.write("${element.f ?? ""}\t");
                            sb.write("${element.g ?? ""}\t");
                            sb.write("${element.h ?? ""}\t");
                            sb.write("${element.i ?? ""}\t");
                            sb.write("${element.j ?? ""}\t");
                            sb.write("${element.k ?? ""}\t");
                            sb.write("${element.l ?? ""}\t");
                            sb.write("${element.m ?? ""}\t");
                            sb.write("${element.n ?? ""}\t");
                            sb.write("${element.o ?? ""}\t");
                            sb.write("${element.p ?? ""}\t");
                            sb.write("${element.q ?? ""}\t");
                            sb.write("${element.r ?? ""}\t");
                            sb.write("${element.s ?? ""}\t");
                            sb.write("'${element.t ?? ""}\t");
                            sb.write("${element.u ?? ""}\t");

                            sb.write("\n");
                          }
                          sb.toString().copyValue();
                        },
                        child: Text("允许复制或者右侧的写入")),
                    SizedBox(width: 10),
                    Container(
                      decoration: BoxDecoration(border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(10)),
                      width: 200,
                      height: 100,
                      child: Column(
                        children: [
                          Expanded(
                              child: DropTarget(
                                  onDragDone: (data) {
                                    // 运单管理
                                    writeFile = File(data.files.first.path);
                                    setState(() {});
                                  },
                                  child: Container(
                                    color: Colors.blue.withOpacity(0.4),
                                    child: writeFile != null
                                        ? Center(
                                            child: Text("${writeFile!.path.split('\\').last}"),
                                          )
                                        : const Center(child: Text("拖动文件到此处")),
                                  ))),
                          SizedBox(
                            height: 50,
                            width: 100,
                            child: TextField(
                                onChanged: (value) {
                                  writeName = value;
                                },

                                decoration: InputDecoration(border: OutlineInputBorder(), labelText: "写入的文件名")),
                          ),
                        ],
                      ),
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    ElevatedButton(
                        onPressed: () {
                          if (cpcFileResultList.isEmpty) {
                            showSnackBar(Text("请先提取数据"));
                            return;
                          }
                          _cpcReportBloc?.add(CpcFileWriteFileEvent(
                            cpcResultList: cpcFileResultList,
                            writeFile: writeFile!,
                            writeName: writeName.toString(),
                          ));
                        },
                        child: Text("开始写入")),
                  ],
                ),
                Text("$writeMsg"),
                if (writeFileLoadingState)
                  Center(
                    child: LinearProgressIndicator(
                      value: margeProgress,
                      minHeight: 10,
                      borderRadius: BorderRadius.circular(10),
                    ),
                  ),
                Container(
                  decoration: BoxDecoration(border: Border.all(color: Colors.grey), borderRadius: BorderRadius.circular(10)),
                  width: double.infinity,
                  height: 500,
                  padding: EdgeInsets.all(10),
                  margin: EdgeInsets.all(10),
                  child: SingleChildScrollView(
                    child: Column(
                      children: [
                        Text("数据合并结果"),
                        Table(
                          border: TableBorder.all(color: Colors.black),
                          children: [
                            TableRow(children: [...headeData.map((e) => TableCell(child: Text(e, textAlign: TextAlign.center)))]),
                            ...cpcFileResultList.map((element) {
                              return TableRow(children: [
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.a ?? ""}", maxLines: 2))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.b ?? ""}", maxLines: 2, style: TextStyle(color: Colors.orange)))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.c ?? ""}", style: TextStyle(color: Colors.orange), maxLines: 2))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.d ?? ""}", style: TextStyle(color: Colors.orange)))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.e ?? ""}", maxLines: 2, style: TextStyle(color: Colors.green)))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.f ?? ""}", style: TextStyle(color: Colors.orange), maxLines: 2))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.g ?? ""}", style: TextStyle(color: Colors.green), maxLines: 2))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.h ?? ""}", maxLines: 2))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.i ?? ""}"))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.j ?? ""}", style: TextStyle(color: Colors.blue)))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.k ?? ""}", maxLines: 2))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.l ?? ""}", maxLines: 2))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.m ?? ""}"))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.n ?? ""}", maxLines: 2))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.o ?? ""}", style: TextStyle(color: Colors.blue), maxLines: 2))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.p ?? ""}", maxLines: 2))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.q ?? ""}", maxLines: 2))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.r ?? ""}"))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.s ?? ""}", maxLines: 2))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.t ?? ""}", maxLines: 2, style: TextStyle(color: Colors.green)))),
                                TableCell(child: Container(alignment: Alignment.center, child: Text("${element.u ?? ""}", maxLines: 2))),
                              ]);
                            })
                          ],
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
        floatingActionButton: FloatingActionButton(child: BackButton(), onPressed: () {}));
  }
}

/**
 *  运单管理
 *  G 》F
 *  E >B
 *  D>C
 *  M>D
 *  H>I
 *  CF>T  标识
 *
 *
 *  FI
    D  标识
 *  J>J
 *  K>U
 *
 *  中有文件
 *  A  >E
 *  B  >N
 *  I  标识
 *  K>L
 *  R>G
 *
 *
 */